package com.zunipe.accounts.database.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zunipe.accounts.database.AccountDBHelper;
import com.zunipe.accounts.database.entity.User;

public class UserDao {
    private final AccountDBHelper dbHelper;

    public UserDao(Context context) {
        dbHelper = new AccountDBHelper(context);
    }

    public User findByUsername(String username) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        try (Cursor cursor = database.rawQuery("SELECT * FROM users", new String[]{})) {
            if (cursor.moveToNext()) {
                int id = cursor.getInt(0);
                //String username = cursor.getString(1);
                String password = cursor.getString(2);
                return new User(id, username, password);
            }
        }
        return null;
    }

    public int insert(User user) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.execSQL("INSERT INTO users(username, password) VALUES(?, ?)", new Object[]{user.getUsername(), user.getPassword()});
        try (Cursor cursor = database.rawQuery("SELECT last_insert_rowid()", new String[]{})) {
            if (cursor.moveToNext()) {
                return cursor.getInt(0);
            }
        }
        return -1;
    }

    public void update(User user) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.execSQL("UPDATE users SET password = ? WHERE id = ?", new Object[]{user.getId()});
    }
}
